<template>
  <div id="BodyAndExercise">
    <van-nav-bar fixed left-arrow left-text="返回" placeholder title="身体及运动" @click-left="back"/>
    <div class="main">
      <van-form ref="vanForm">
        <van-row align="center" justify="space-between" type="flex">
          <van-col span="21"
          >
            <van-field
              v-model="form.tizhong"
              required
              label="当前体重"
              maxlength="6"
              placeholder="请输入"
              type="number"
            />
          </van-col>
          <van-col :offset="1" class="company" span="2">kg</van-col>
        </van-row>
<!--        <van-row align="center" justify="space-between" type="flex">-->
<!--          <van-col span="21"-->
<!--          >-->
<!--            <van-field-->
<!--              v-model="form.tizhong_old"-->
<!--              label="一个月前体重"-->
<!--              maxlength="6"-->
<!--              placeholder="请输入"-->
<!--              type="number"-->
<!--            />-->
<!--          </van-col>-->
<!--          <van-col :offset="1" class="company" span="2">kg</van-col>-->
<!--        </van-row>-->
<!--        <van-row align="center" justify="space-between" type="flex">-->
<!--          <van-col span="21"-->
<!--          >-->
<!--            <van-field-->
<!--              v-model="form.tiwen"-->
<!--              label="体温"-->
<!--              maxlength="6"-->
<!--              placeholder="请输入"-->
<!--              type="number"-->
<!--            />-->
<!--          </van-col>-->
<!--          <van-col :offset="1" class="company" span="2">℃</van-col>-->
<!--        </van-row>-->
        <van-row align="center" justify="space-between" type="flex">
          <van-col span="21"
          >
            <van-field
              v-model="form.woli"
              label="握力"
              maxlength="6"
              placeholder="请输入"
              type="number"
            />
          </van-col>
          <van-col :offset="1" class="company" span="2">kg</van-col>
        </van-row>
        <van-row align="center" justify="space-between" type="flex">
          <van-col span="21"
          >
            <van-field
              v-model="form.tizhilv"
              label="去脂体重"
              maxlength="6"
              placeholder="请输入"
              type="number"
            />
          </van-col>
          <van-col :offset="1" class="company" span="2">kg</van-col>
        </van-row>

        <div class="upload">
          <!--          {{fileList}}-->
          <!--          <div v-for="(item,index) in fileList" :key="index">-->
          <!--            <img :src="item.replace(/\\/g,'/')" alt="">-->
          <!--          </div>-->
          <div class="title">请上传图片及视频</div>
          <van-uploader
            v-model="fileList"
            :after-read="shentiMedia"
            :before-delete="deleteImg"
            :before-read="sbeforeRead"
          >
            <img alt="" src="@/assets/images/addjkrz.png"/>
          </van-uploader>
         
        </div>

<!--        <van-row-->
<!--          :class="form.is_huodong == 0 ? 'bbn' : ''"-->
<!--          align="center"-->
<!--          justify="space-between"-->
<!--          type="flex"-->
<!--        >-->
<!--          <van-field input-align="right" label="是否活动" name="radio">-->
<!--            <template #input>-->
<!--              <van-radio-group v-model="form.is_huodong" direction="horizontal">-->
<!--                <van-radio :name="1">有</van-radio>-->
<!--                <van-radio :name="0">无</van-radio>-->
<!--              </van-radio-group>-->
<!--            </template>-->
<!--          </van-field>-->
<!--        </van-row>-->



        <!-- <van-row
          align="center"
          type="flex"
          justify="end"
        >
          <van-col span="24"
          >
            <van-field
              label="下床活动"
              input-align="right"
              type="number"
            >
              <template #input>
                <select v-model="form.xiachuang_time">
                  <option value="多数时间卧床">多数时间卧床</option>
                  <option value="多数时间活动">多数时间活动</option>
                </select>
              </template>
            </van-field>
          </van-col>
        </van-row> -->

         <van-row
          align="center"
          type="flex"
          justify="end"
        >
          <van-col span="24">
            <div class="xiachuang">
              <div class="tit">
                <span class="title"
              >下床活动</span
              >
              </div>
              <div id="xchuang" @click="xiachuang($event)">
                <span v-for="item in ['多数时间卧床','多数时间活动',]" id="xiachuang" :key="item">
                  {{ item }}
                </span>
              </div>
            </div>
            <!-- <van-field
              label="下床活动"
              input-align="right"
              type="number"
            >
              <template #input>
                <select v-model="form.xiachuang_time">
                  <option value="多数时间卧床">多数时间卧床</option>
                  <option value="多数时间活动">多数时间活动</option>
                </select>
              </template>
            </van-field> -->
          </van-col>
        </van-row>

       
       
        <van-row
          align="center"
          justify="end"
          type="flex"
        >
          <van-col span="24">
            
            <div class="buxing">
              <div class="tit">
                <span class="title">步行时间</span>
              </div>
              <div id="bxing" @click="buxing($event)">
                <span v-for="item in ['小于30分钟','30分钟—60分钟','大于一小时']" id="buxing" :key="item">
                  {{ item }}
                </span>
              </div>
            </div>



            <!-- <van-field
              label="步行时间"
              input-align="right"
              type="number"
            >
              <template #input>
                <select v-model="form.buxing_time">
                  <option value="小于30分钟">小于30分钟</option>
                  <option value="30分钟—60分钟">30分钟—60分钟</option>
                  <option value="大于一小时">大于一小时</option>
                </select>
              </template>
            </van-field> -->
          </van-col>
        </van-row>
      </van-form>
<!--      <div  class="upload">-->
<!--        <div class="title">请上传图片及视频</div>-->
<!--        <van-uploader-->
<!--          v-model="fileList1"-->
<!--          :after-read="huodongMedia"-->
<!--          :before-delete="deleteImg1"-->
<!--          :before-read="beforeRead"-->
<!--        >-->
<!--          <img alt="" src="@/assets/images/addjkrz.png"/>-->
<!--        </van-uploader>-->
<!--      </div>-->
      <van-button round type="info" @click="submit">保存并提交</van-button>
    </div>
  </div>
</template>

<script>
import {upFiles} from "@/apis/journal";
import {addHealthLog} from "@/apis/journal";
import apiConfig from "../../../config/api.config";
// 图片压缩
import {uploadImgs} from "../../../config/upload"

export default {
  data() {
    return {
      uploadImgs,
      apiConfig,
      form: {
        action: "add",
        part: 1,
        tizhong: "",
        tizhong_old: "",
        tiwen: "",
        woli: "",
        tizhilv: "",
        shenti_media: [],
        is_huodong: "",
        xiachuang_time: "多数时间卧床",
        buxing_time: "小于30分钟",
        huodong_media: [],
      },
      fileList: [],
      fileList1: []
    };
  },
  methods: {
    back() {
      this.$router.go(-1); //返回上一层
    },
    xiachuang(el) {
      if (el.target.localName !== "div") {
        let doc = document.querySelector("#xchuang");
        for (let i = 0; i < doc.children.length; i++) {
          if (doc.children[i].className) {
            doc.children[i].setAttribute("class", "");
          }
        }
        el.target.setAttribute("class", "active");
        this.form.xiachuang_time = el.target.innerText;
        console.log(this.form.xiachuang_time)
      }
    },
    buxing(el) {
      if (el.target.localName !== "div") {
        let doc = document.querySelector("#bxing");
        for (let i = 0; i < doc.children.length; i++) {
          if (doc.children[i].className) {
            doc.children[i].setAttribute("class", "");
          }
        }
        el.target.setAttribute("class", "active");
        this.form.buxing_time = el.target.innerText;
        console.log(this.form.buxing_time)
      }
    },
    beforeRead(file) {
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/jpg" &&
        file.type !== "image/gif" &&
        file.type !== "image/png" &&
        file.type !== "video/mp4"
      ) {
        this.$toast("请上传 .jpg，.png，.gif 格式图片或视频");
        return false;
      }
      return true;
    },
    sbeforeRead(file) {
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/jpg" &&
        file.type !== "image/gif" &&
        file.type !== "image/png" &&
        file.type !== "video/mp4"
      ) {
        this.$toast("请上传 .jpg，.png，.gif 格式图片或视频");
        return false;
      }
      return true;
    },

    shentiMedia(file) {

      file.status = 'uploading';
      file.message = '上传中...';
      file.status = 'uploading';
      file.message = '上传中...';
      this.disabled = true
      this.uploadImgs(file)
      setTimeout(() => {
        if (sessionStorage.getItem('base64') != '' && sessionStorage.getItem('base64') != null) {
          upFiles({file: sessionStorage.getItem('base64')})
            .then(res => {
              if (res.codes == "200") {
                this.form.shenti_media.push(res.data);
                file.status = '';
                file.message = '';
                this.disabled = false
              } else {
                file.status = 'failed';
                file.message = '上传失败';
                this.disabled = false
              }
            })
            .catch(err => {
              this.disabled = false
              file.status = 'failed';
              file.message = '上传失败';
              this.$toast("上传失败");

            });
          sessionStorage.removeItem('base64')
        } else {
          file.status = 'failed';
          file.message = '上传失败';
          this.$toast("上传失败");
        }
      }, 1600)

      // upFiles(file)
      //   .then(res => {

      //     file.status = '';
      //     file.message = '';
      //     let arr = res.data;
      //     arr.forEach(item => {
      //       this.form.shenti_media.push(item);
      //     });
      //   })
      //   .catch(err => {

      //     file.status = 'failed';
      //     file.message = '上传失败';
      //     this.$toast(err.msg);
      //   });

    },
    huodongMedia(file) {
      file.status = 'uploading';
      file.message = '上传中...';
      this.uploadImgs(file)
      setTimeout(() => {
        if (sessionStorage.getItem('base64') != '' && sessionStorage.getItem('base64') != null) {
          upFiles({file: sessionStorage.getItem('base64')})
            .then(res => {
              if (res.codes == "200") {
                this.form.huodong_media.push(res.data);
                file.status = '';
                file.message = '';
                this.disabled = false
              } else {
                file.status = 'failed';
                file.message = '上传失败';
                this.disabled = false
              }
            })
            .catch(err => {
              this.disabled = false
              file.status = 'failed';
              file.message = '上传失败';
              this.$toast("上传失败");

            });
          sessionStorage.removeItem('base64')
        } else {
          file.status = 'failed';
          file.message = '上传失败';
          this.$toast("上传失败");
        }
      }, 1600)

      // upFiles(file)
      //   .then(res => {
      //     file.status = '';
      //     file.message = '';
      //     let arr = res.data;
      //     arr.forEach(item => {
      //       this.form.huodong_media.push(item);
      //     });
      //   })
      //   .catch(err => {
      //     file.status = 'failed';
      //     file.message = '上传失败';
      //     this.$toast(err.msg);
      //   });
    },
    submit() {
      this.form.action = "add";
      // 复康日志版本
      this.form.yemian = apiConfig.journal
      if (this.form.tizhong === "") {
        this.$toast('请填写体重！')

      }
      // else if (this.form.tiwen === "") {
      //   this.$toast('请填写体温！')
      //
      // }
        else {
        addHealthLog(this.form)
          .then(res => {
            this.$toast("添加成功");
            this.$router.go(-1);
            this.form.id = res.data.id;
            let expire = new Date(
              new Date().setDate(new Date().getDate() + 1)
            ).setHours(0, 0, 0, 0);
            this.localStorageSet("id", res.data.id, expire);
            this.localStorageSet("ssyd", this.form, expire);
          })
          .catch(err => {
            if (err.msg) {
              this.$toast(err.msg);
            } else {
              this.$toast('网络错误');
            }
          });
      }

    },
    bodylist() {
      this.form.action = "list"
      addHealthLog(this.form)
        .then(res => {
          const data = res.data.list
          for (const i in data) {
            for (const it in this.form) {
              if (i === it) {
                this.form[it] = data[i]
              }
            }
          }
          if (this.form.shenti_media) {
            this.form.shenti_media.forEach(item => {
              item = apiConfig.imgUrl + item.replace(/\\/g, "/");
              this.fileList.push({url: item});
            })
          }
          if (this.form.huodong_media) {
            this.form.huodong_media.forEach(item => {
              item = apiConfig.imgUrl + item.replace(/\\/g, "/");
              this.fileList1.push({url: item});
            })
          }
          // 睡眠时长
          if (this.form.xiachuang_time !== null) {
            if (this.form.xiachuang_time == '多数时间卧床') {
              const xbian = document.getElementById("xchuang");
              xbian.children[0].className = "active";
            } else if (this.form.xiachuang_time == '多数时间活动') {
              const xbian = document.getElementById("xchuang");
              xbian.children[1].className = "active";
            }
          }else {
            this.form.xiachuang_time = '多数时间卧床'
            const xbian = document.getElementById("xchuang");
            xbian.children[0].className = "active";
          }
          // 步行时长
          if (this.form.buxing_time !== null) {
            if (this.form.buxing_time == '小于30分钟') {
              const xbian = document.getElementById("bxing");
              xbian.children[0].className = "active";
            } else if (this.form.buxing_time == '30分钟—60分钟') {
              const xbian = document.getElementById("bxing");
              xbian.children[1].className = "active";
            }else if (this.form.buxing_time == '大于一小时') {
              const xbian = document.getElementById("bxing");
              xbian.children[2].className = "active";
            }
          }else {
            this.form.buxing_time = '小于30分钟'
            const xbian = document.getElementById("bxing");
            xbian.children[0].className = "active";
          }
        })
        .catch(err => {
          if (err.msg) {
            this.$toast(err.msg);
          } else {
            this.$toast('网络错误');
          }
        });
    },
    //  删除图片
    deleteImg(detail, $event) {
      this.fileList.forEach((item, index) => {
        if ($event.index == index) {
          this.fileList.splice(index, 1)
          this.form.shenti_media.splice(index, 1)
        }
      })
    },
    deleteImg1(detail, $event) {
      this.fileList1.forEach((item, index) => {
        if ($event.index == index) {
          this.fileList1.splice(index, 1)
          this.form.huodong_media.splice(index, 1)
        }
      })
    },

  },
  mounted() {
    this.form.hzid = this.$route.params.hzid
    let id = this.localStorageGet("id");
    if (id) {
      this.form.id = id;
    }
    this.bodylist()
    // let detail = this.localStorageGet("ssyd");

    // if (detail) {
    //   this.form = detail || {
    //     action:"add",
    //     part: 1,
    //     tizhong: "",
    //     tizhong_old: "",
    //     tiwen: "",
    //     woli: "",
    //     tizhilv: "",
    //     shenti_media: [],
    //     is_huodong: "",
    //     xiachuang_time: "",
    //     buxing_time: "",
    //     huodong_media: []
    //   };
    //   this.form.shenti_media.forEach(item=>{
    //     item = apiConfig.baseUrl + item.replace(/\\/g, "/");
    //       this.fileList.push({url:item});
    //   })
    //   this.form.huodong_media.forEach(item=>{
    //     item = apiConfig.baseUrl + item.replace(/\\/g, "/");
    //     this.fileList1.push({url:item});
    //   })
    // }
  }
};
</script>

<style lang="less">
#BodyAndExercise {
  .van-cell--required::before {
    position: absolute;
    left: 0px;
    color: #ee0a24;
    font-size: 14px;
    content: '*';
  }
  .xiachuang{
      //border-bottom: 1px solid #d2d2d2;
      margin-top: 10px;
      .title {
        // font-size: 17px;
        display: block;
        width: 100%;
        text-align: left;
        vertical-align: middle;
      }

      #xchuang{
        margin: 15px 10px;
        display: flex;
        align-items: center;
        #xiachuang{
        
          width: fit-content;
          height: 22px;
          line-height: 22px;
          text-align: center;
          border: 1px solid rgba(0, 0, 0, 1);
          margin-right: 6px;
          margin-bottom: 10px;
          border-radius: 5px;
          padding: 0 10px;
           &.active {
              background: #5297ff;
            }
          &:last-child {
            margin-right: 0;
          }
        }
      }
  }
  .buxing{
      //border-bottom: 1px solid #d2d2d2;
      margin-top: 10px;
      .title {
        // font-size: 17px;
        display: block;
        width: 100%;
        text-align: left;
        vertical-align: middle;
      }

      #bxing{
        margin: 15px 10px;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        #buxing{
        
          width: fit-content;
          height: 22px;
          line-height: 22px;
          text-align: center;
          border: 1px solid rgba(0, 0, 0, 1);
          margin-right: 6px;
          margin-bottom: 10px;
          border-radius: 5px;
          padding: 0 10px;
           &.active {
              background: #5297ff;
            }
          &:last-child {
            margin-right: 0;
          }
        }
      }
  }
  .main {
    padding: 10px;
    background-color: #fff;

    .van-row {
      border-bottom: 1px solid #ebedf0;
      &:last-child{
        border-bottom: 0;
      }
      &.bbn {
        border-bottom: none;
      }

      .van-cell {
        padding: 10px 5px;

        .van-cell__title {
          font-size: 15px;
        }
      }
    }

    .upload {
      margin-top: 18px;
      text-align: left;
      margin-bottom: 32px;

      .title {
        margin-bottom: 15px;
        font-size: 15px;
        color: #151515;
      }

      img {
        width: 80px;
        height: 80px;
      }

      .van-image {
        width: 80px;
        height: 80px;
      }

      .van-uploader__file {
        width: 80px;
        height: 80px;
      }
    }

    .van-button {
      width: 281px;
      height: 37px;
      font-size: 17px;
    }
  }
}
</style>
